package com.cenluan.kit;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求工具类
 * 
 * @author peak
 * 
 */
public class RequestKit {
	/**
	 * 获取二级域名前缀，如www.baidu.com返回www<br>
	 * 如果请求的Host是一级域名（如baidu.com）或者localhost返回空
	 * 
	 * @param req
	 *            请求
	 * @return
	 */
	public static String getSLDPrefix(HttpServletRequest req) {
		String serverName = req.getServerName();
		if (serverName.matches("^.+\\..+\\..+$")) {
			return serverName.substring(0, serverName.indexOf("."));
		}
		return null;
	}

	/**
	 * 获取客户端真实ip，适用于使用了代理的情况
	 * 
	 * @param req
	 * @return
	 */
	public static String getClientIp(HttpServletRequest req) {
		String ip = req.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getHeader("proxy-client-ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = req.getRemoteAddr();
		}
		// 如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
		// 取X-Forwarded-For中第一个非unknown的有效IP字符串
		// 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
		// 192.168.1.100
		// 用户真实IP为： 192.168.1.110
		if (ip.indexOf(",") != -1) {
			for (String str : ip.split(",")) {
				if (!"unkown".equalsIgnoreCase(str)) {
					ip = str;
					break;
				}
			}
		}
		return ip;
	}

	/**
	 * 获取servername，适用于代理的情况，包含端口号
	 * 
	 * @param req
	 * @return
	 */
	public static String getServerName(HttpServletRequest req) {
		String serverName = req.getHeader("X-FORWARDED-HOST");
		if (serverName == null || serverName.length() < 1) {
			serverName = req.getServerName()
					+ (req.getServerPort() == 80 ? "" : (":" + req
							.getServerPort()));
		} else if (serverName.contains(",")) {
			serverName = serverName.substring(0, serverName.indexOf(","))
					.trim();
		}
		return serverName;
	}

	/**
	 * 获取访问url的前缀，从http://一直包含到contextPath
	 * 
	 * @param req
	 * @return
	 */
	public static String getUrlPrefix(HttpServletRequest req) {
		String url = req.getScheme() + "://";
		url += getServerName(req);
		if (req.getServerPort() != 80) {
			url += ":" + req.getServerPort();
		}
		url += req.getContextPath();
		return url;
	}
}
